
import { login, getUserInfo, getUserDetail } from '@/api/user'
import { setToken, getToken, removeToken, setTimestamp } from '@/utils/auth'

const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  setUserInfo(state, data) {
    state.userInfo = data
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login(store, formData) {
    const data = await login(formData)
    // console.log('action成功逻辑')
    store.commit('setToken', data)
    setTimestamp()
  },
  async getUserInfo(store) {
    const res = await getUserInfo()
    const detail = await getUserDetail(res.userId)
    store.commit('setUserInfo', {
      ...res,
      ...detail
    })
  },
  logout(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
